<template>
  <div class="button-box">
    <div class="btn" v-if="isOk == '0'">
      <!-- <img :src="require(`@/assets/${systemcolor}/face_icon.png`)" alt="" @click="handleClick"/> -->
      <div class="text">人脸验证仅能由本人完成，以确认是客户本人在操作,该授权仅对本次操作有效</div>
      <div class="matter_list">
        <div class="item_one" v-for="(item,index) in matterList" :key="index">
          <div class="icon_box">
            <img :src="item.icon" alt=""/>
          </div>
          <p>{{ item['text'] }}</p>
        </div>
      </div>
    </div>
    <div class="btn" v-else-if="isOk == '1'">
      <!-- <img :src="require('@/assets/recognize-success.png')" alt=""/> -->
      <div class="text">恭喜您，人脸验证通过</div>
    </div>
    <div class="btn" v-else>
      <!-- <img :src="require(`@/assets/${systemcolor}/face_err.png`)" alt=""/> -->
      <div class="text">很抱歉，人脸验证失败！</div>
      <!--      <ul class="describe">-->
      <!--        <li><span></span>确保本人面部出现在框内</li>-->
      <!--        <li><span></span>确保面部与屏幕保持适当距离</li>-->
      <!--        <li><span></span>保持光线充足和均匀</li>-->
      <!--        <li><span></span>摘掉眼镜并露出耳朵</li>-->
      <!--      </ul>-->
      <div class="matter_list">
        <div class="item_one" v-for="(item,index) in matterList" :key="index">
          <div class="icon_box">
            <!--            <img :src="require(item.icon)" alt=""/>-->
          </div>
          <p>{{ item['text'] }}</p>
        </div>
      </div>
      <div class="footer-btn">
        <x-button action-type="button" plain @click.native="handleClick">
          重新识别
          <span>{{ count ? '(' + count + 's)' : "" }}</span>
        </x-button>
      </div>
    </div>
    <!-- <x-button action-type="button" type="primary" @click.native="change">切换页面</x-button> -->
  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import md5 from "js-md5";

export default {
  name: "gzFaceVerification",
  props: {
    identityinfo: {
      //配置用户名 身份证号码
      type: Object,
      default: {},
    },
    triggerMode: {
      type: String,
      default: "auto", // auto 为自动触发人脸识别，click 为需要点击触发
    },
    value: 0,
  },
  data() {
    return {
      latestUrl: "",
      isOk: this.value ? Number(this.value) : 0,
      isDisable: false,
      schema: "",
      count: null,
      matterList: [
        {
          // icon: require('@/assets/003.png'),
          text: '正对手机'
        },
        {
          // icon: require('@/assets/002.png'),
          text: '避免遮挡'
        },
        {
          // icon: require('@/assets/001.png'),
          text: '光线充足'
        }
      ],
      systemcolor: ''
    };
  },
  created() {
    let that = this
    that.count = 5
    let timer = setInterval(() => {
      that.count--
      if (that.count <= 0) {
        that.count = null
        clearInterval(timer)
        //  自动重新识别
      }
    }, 1000)
  },
  mounted() {
    this.systemcolor = localStorage.getItem("systemColor")
    // console.log(this.identityinfo)
    //获取UA信息
    // let ua = this.$bridge.getDeviceType();
    // this.schema = ua;
    // if (ua.indexOf("rdsgzapp/android") != -1) {
    //   this.schema = "android";
    //   // 接收调用原生人脸识别后返回的信息
    //   window.callBackLiveParam = (faceInfo) => {
    //     // 返回数据事例
    //     // {"message":"动作活体检测耗时:695 攻击类型:1","code":0,"success":true,"data":{"code":1}}
    //     if (faceInfo.success) {
    //       this.isOk = 1;
    //     } else {
    //       this.isOk = 2;
    //     }
    //     let info = {
    //       ErrMsg: faceInfo.message,
    //       ErrCode: faceInfo.code,
    //     };
    //     this.$emit("getverification", info);
    //     this.$emit("input", this.isOk == 1 ? true : false);
    //   };
    // } else if (ua.indexOf("rdsgzapp/ios") != -1) {
    //   this.schema = "ios";
    // } else {
    // console.info('uaType => ' + ua)
    // if (ua != "android" && ua != "ios") {
    //   // console.log('routeQuery => ', this.$route.query)
    //   let bizToken = this.getParam('bizToken')
    //   let taskId = this.getParam('taskId')
    //   let UnionId = this.getParam('UnionId')
    //   let ChannelId = this.getParam('ChannelId')
    //   let timeStamp = this.getParam('timeStamp')
    //   let sign = this.getParam('sign')
    //   let signValue = `${taskId}${UnionId}GZB${ChannelId}${bizToken}${timeStamp}`
    //   let sigemd = md5(signValue)
    //   let instId = this.identityinfo.instId;
    //   let filetype = this.identityinfo.fileType;
    //   if (bizToken) {
    //     if (sign == sigemd) {
    //       this.getVerificationInfo(bizToken, instId, filetype);
    //     } else {
    //       this.abTools.toast("人脸识别校验失败，请稍后重试！", "warn")
    //     }
    //   } else {
    //     let isOk = this.value ? Number(this.value) : 0;
    //     if (this.triggerMode == "auto" && isOk == 0) {
    //       this.handleClick();
    //     }
    //   }
    // } else {
    //   let isOk = this.value ? Number(this.value) : 0;
    //   if (this.triggerMode == "auto" && isOk == 0) {
    //     this.handleClick();
    //   }
    // }
  },
  methods: {
    change() {
      if (this.isOk == 2) {
        this.isOk = 0;
      } else {
        this.isOk++;
      }
    },
    getParam(name) {
      var locUrl = window.location.search.substr(1);
      var aryParams = locUrl.split("&");
      var rtn = "";
      for (var i = 0; i < aryParams.length; i++) {
        var pair = aryParams[i];
        var aryEnt = pair.split("=");
        var key = aryEnt[0];
        var val = aryEnt[1];
        if (key != name) continue;
        if (rtn == "") {
          rtn = val;
        } else {
          rtn += "," + val;
        }
      }
      return rtn;
    },
    getHidestr(str, type) {
      let newStr = ''
      if (str === 0 || str) {
        str += ''
        if (type == 'idCard') { //身份证类型  隐藏证件号中间的月日
          newStr += str.substr(0, 6)
          for (let i = 6; i < str.length; i++) {
            newStr += '*'
          }
        } else if (type == 'nameself') { //本人姓名
          if (str.length <= 3) { //小于三位 隐藏名
            newStr += str.substring(0, 1)
            for (let i = 1; i < str.length; i++) {
              newStr += '*'
            }
          } else { //大于三位 显示前2位 其余隐藏
            newStr += str.substring(0, 2)
            for (let i = 2; i < str.length; i++) {
              newStr += '*'
            }
          }
        } else {
          newStr = str
        }
      }
      return newStr
    },
    getAppResult(base64) {
      return new Promise((resolve, reject) => {
        this.baseService
          .post(this.__ctx + "/UAP/uap6026106", {
            name: this.identityinfo.name,
            idCard: this.identityinfo.idCard,
            idCardType: "101",
            instId: this.identityinfo.instId,
            fileType: this.identityinfo.fileType,
            face: base64.FileDataOne,
            video: base64.LivenessData,
          })
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
    handleClick() {
      //开始进行人脸验证
      if (this.schema == "android" || this.schema == "ios") {
        this.$bridge.goface(null, (identityInfo) => {
          // console.log(identityInfo,Object.keys(identityInfo))
          if (identityInfo) {
            // this.isOk = 1;
            this.$vux.loading.show({
              text: "人脸校验中..."
            })

            this.getAppResult(JSON.parse(identityInfo))
              .then((res) => {
                this.$vux.loading.hide();
                if (res.isOk) {
                  this.isOk = 1;
                  this.$emit("input", this.isOk);
                } else {
                  this.abTools.toast(res.msg, "warn");
                  let info = {
                    ErrMsg: "人脸识别失败",
                    ErrCode: "error",
                  };
                  this.$emit("getverification", info);
                  this.$emit("input", this.isOk);
                }
              })
              .catch((err) => {
                this.$vux.loading.hide();
                this.abTools.toast("人脸校验失败，请稍后重试！", "warn");
                this.isOk = 2;
                let info = {
                  ErrMsg: "人脸识别失败",
                  ErrCode: "error",
                };
                this.$emit("getverification", info);
                this.$emit("input", this.isOk);
              });
          } else {
            this.isOk = 2;
            let info = {
              ErrMsg: "人脸识别失败",
              ErrCode: "error",
            };
            this.$emit("getverification", info);
            this.$emit("input", this.isOk);
          }
        });
      } else {
        // let bizToken = this.$route.query.BizToken;
        let taskId = this.$route.query.taskId;
        // if (bizToken) {
        //   this.latestUrl = winhref.substring(
        //     0,
        //     winhref.indexOf("BizToken") - 1
        //   );
        // } else {
        //   this.latestUrl = winhref;
        // }
        let url = this.__ctx + "/tencentCloud/face/getTencentBizToken";
        let config = {
          redirectUrl: "",
          idCard: this.identityinfo.idCard || "",
          name: this.identityinfo.name || "",
        };
        if (this.isDisable) {
          return false;
        }
        this.isDisable = true;
        let nameHide = this.getHidestr(config.name, 'nameself')
        let idCardHide = this.getHidestr(config.idCard, 'idCard')
        // window.open('https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx1f7125112b74db52&redirect_uri=https%3A%2F%2Fopen.faceid.qq.com%2Fv1%2Fapi%2FgetCode%3FbizRedirect%3Dhttps%253A%252F%252Ffaceid.qq.com%252Fapi%252Fauth%252FgetOpenidAndSaveToken%253Ftoken%253DF8003CCB-2352-4DAF-A94F-37CFCB927CCF&response_type=code&scope=snsapi_base&state=&component_appid=wx9802ee81e68d6dee#wechat_redirect','_self')
        // return false
        this.baseService
          .postForm(url, config)
          .then((res) => {
            this.isDisable = false;
            if (res.isOk) {
              wx.miniProgram.navigateTo({
                url: `znwdFace/znwdFace?bizToken=${res.data.bizToken}&name=${nameHide}&IdNo=${idCardHide}&redirect=${taskId}`,
              });
              // let openUrl = res.data.url;
              // window.open(openUrl, "_self");
            } else {
              this.abTools.toast("请求失败，请稍后再试！", "warn");
            }
          })
          .catch((err) => {
            this.isDisable = false;
            this.abTools.toast("数据不正确，请求失败，请稍后再试！", "warn");
            console.log(err);
          });
      }
    },
    getVerificationInfo(bizToken, instId, filetype) {
      //、获取人脸验证结果
      let url = this.__ctx + "/tencentCloud/face/getDetectInfo";
      let config = {
        bizToken: bizToken,
        instId: instId,
        fileType: filetype
      };
      this.baseService
        .postForm(url, config)
        .then((res) => {
          if (res.isOk) {
            if (res.data.Text.ErrCode === 0) {
              this.isOk = 1;
            } else {
              this.isOk = 2;
            }
            this.$emit("getverification", res.data.Text);
            this.$emit("input", this.isOk);
          }
        })
        .catch((err) => {
        });
    },
  },
  watch: {
    value(newValue, oldValue) {
      this.isOk = newValue;
    },
  },
};
</script>

<style lang="less" scoped>
.button-box {
  text-align: center;
  padding: 2.4rem 0rem 2rem 0;
  border-radius: 8px;
  margin: 0 1.2rem;
  background-color: #FFFFFF;

  .btn {
    //display: inline-block;
    //position: relative;

    > img {
      width: 11.6rem;
      height: 11.6rem;
      margin: 1.6rem 0;
    }

    .text {
      width: 26rem;
      margin: 2rem auto;
      color: #4E5969;
      font-family: HarmonyOS Sans SC;
      font-size: 1.4rem;
      font-weight: 400;
      line-height: 20px;
      text-align: center;
    }

    //新增模块
    .matter_list {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 1.6rem;

      .item_one {
        width: 9.3rem;
        height: 6.6rem;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: space-between;

        .icon_box {
          width: 4.4rem;
          height: 4.4rem;
          border-radius: 24px;
          background-color: #F2F2F6;
          margin-bottom: .8rem;
          display: flex;
          align-items: center;
          justify-content: center;

          img {
            //margin: 1rem;
            width: 2.4rem;
            //height: 100%;
          }
        }

        p {
          color: rgb(134, 144, 156);
          font-family: HarmonyOS Sans SC;
          font-size: 14px;
          font-weight: 400;
          line-height: 16px;
        }
      }
    }

    .describe {
      text-align: left;
      color: #4e5969;
      font-size: 1.4rem;
      padding: 1.2rem 0;

      li {
        padding: 0.2rem;

        span {
          display: inline-block;
          width: 0.8rem;
          height: 0.8rem;
          border-radius: 50%;
          background-color: #3f7ad6;
          margin-right: 1rem;
        }
      }
    }

    .footer-btn {
      margin-top: 3rem;

      .weui-btn {
        width: 20rem;
        height: 4.4rem;
        border-radius: 2.4rem;
        color: var(--primary-color);
        border-color: var(--primary-color);
        font-family: HarmonyOS Sans SC;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}
</style>
